#include "manager_view_impl.h"
#include "service_view_impl.h"
#include "manager_ctrl_impl.h"
#include "tools.h"
#include "emis.h"

ManagerViewImpl::ManagerViewImpl(void)
{
	mgrCtrl = new ManagerCtrlImpl;
	srcView = new ServiceViewImpl;
}
	
ManagerViewImpl::~ManagerViewImpl(void)
{
	delete mgrCtrl;
	delete srcView;
}
	
void ManagerViewImpl::loginManager(void)
{
	char user[20] = {};
	char pwd[20] = {};
	char pwd2[20] = "1324";
	
	ifstream ifs(ADMIN_PATH,ios::in);
	if(ifs.good())
	{
		ifs.read(pwd2,sizeof(pwd));	
		pwd2[strlen(pwd2)-1] = '\0';
	}
	
	info("please input user name:");
	get_str(user,sizeof(user));
	
	info("Please input password:");
	get_pwd(pwd,sizeof(pwd),true);
	
	cout << user << " " << pwd2 << strlen(pwd2) << endl;
	
	if(!strcmp("groan",user) && !strcmp(pwd,pwd2))
	{
		menuMgr();
	}
	else
	{
		info("User name or password is wrong!",1.5);
	}
}

void ManagerViewImpl::loginService(void)
{
	char user[20] = {};
	char pwd[20] = {};
	
	info("Please input user name:");
	get_str(user,sizeof(user));
	
	info("Please input password:");
	get_pwd(pwd,sizeof(pwd),true);

	vector<Manager>& mgrArr = mgrCtrl->listMgr();
	for(uint32_t i=0; i<mgrArr.size(); i++)
	{
		if(!strcmp(user,mgrArr[i].getName()) || atoi(user)==mgrArr[i].getId())
		{
			if(!strcmp(pwd,mgrArr[i].getPwd()))
			{
				srcView->menuSrc();
				return;
			}
			else
			{
				info("password is wrong！",1.5);
				return;
			}
		}
	}
	
	info("User doesn't exist！",1.5);	
}

void ManagerViewImpl::menuMgr(void)
{
	while(true)
	{
		clear_screen();
		
		info("******Welcome to the management subsystem******\n");
		info("		1、Add admin\n");
		info("		2、Delete admin\n");
		info("		3、List all admin\n");
		info("		0、Exit\n");
		
		switch(get_cmd('0','3'))
		{
			case '1': addMgr(); break;
			case '2': delMgr(); break;
			case '3': listMgr(); break;
			case '0': return;
		}
	}
}

void ManagerViewImpl::addMgr(void)
{
	char name[20] = {};
	info("Please input user name:");
	get_str(name,sizeof(name));
	
	char pwd[20] = {};
	info("Please input password:");
	get_pwd(pwd,sizeof(pwd),true);
	
	char pwd2[20] = {};
	info("Please input password again:");
	get_pwd(pwd2,sizeof(pwd2),true);
	
	if(strcmp(pwd,pwd2))
	{
		info("Two different passwords entered, failed to add!\n",1.5);
		return;
	}
	
	Manager mgr(name,pwd);
	if(mgrCtrl->addMgr(mgr))
	{
		info("Add admin successful!\n",1.5);
	}
	else
	{
		info("Fail to add admin!\n",1.5);
	}
}

void ManagerViewImpl::delMgr(void)
{
	int id = 0;
	info("Please input admin ID for deletion:");
	cin >> id;
	
	if(mgrCtrl->delMgr(id))
	{
		info("Delete admin successful！\n",1.5);
	}
	else
	{
		info("Fail to delete admin！\n",1.5);
	}
}

void ManagerViewImpl::listMgr(void)
{
	vector<Manager>& mgrArr = mgrCtrl->listMgr();
	for(uint32_t i=0; i<mgrArr.size(); i++)
	{
		cout << mgrArr[i].getId()  << " " << mgrArr[i].getName() << " " << mgrArr[i].getPwd() << endl;
	}
	anykey_continue();
}
